import {createElement, Component, findDOMNode} from 'rax';
import View from 'rax-view';
import Text from 'rax-text';
import Touchable from 'rax-touchable';
import Picture from 'rax-picture';
import Player from 'rax-player';
import Slider from 'rax-slider';
import ScrollView from 'rax-scrollview';
import transition from 'universal-transition';
import { isWeex } from 'universal-env';

const defaultModuleData = {
  isHome: '0',
  modName: '',

  picture: 'https://img.alicdn.com/imgextra/i2/3355153118/TB26_2uaSBYBeNjy0FeXXbnmFXa-3355153118.jpg',
  height: 80,
  hasPic: '1',

  tagWidth: 10,
  tagSelectWidth: 20,
  tagBottom: 20,
  tagBg: '#ffffff',
  tagSelectBg: '#000000',
  tagMargin: 10,

  sliderHeight: 563,
  sliderPictures: [
    {
      picUrl: '//img.alicdn.com/imgextra/i3/3355153118/TB2u2ulo8DH8KJjy1zeXXXjepXa-3355153118.jpg',
      hotUrl: '//m.taobao.com',
    },
    {
      picUrl: '//img.alicdn.com/imgextra/i3/3355153118/TB2u2ulo8DH8KJjy1zeXXXjepXa-3355153118.jpg',
      hotUrl: '//m.taobao.com',
    },
    {
      picUrl: '//img.alicdn.com/imgextra/i3/3355153118/TB2u2ulo8DH8KJjy1zeXXXjepXa-3355153118.jpg',
      hotUrl: '//m.taobao.com',
    },
  ],

  // 图片热区
  imgHot1: {
    screenHeight: 400,
    screenWidth: 750,
    hot: [{
      data: {
        name: 'hot1',
        x: 0,
        y: 0,
        width: 750,
        height: 400,
        url: '//m.taobao.com/'
      }
    }],
    img: [{
      data: {
        name: 'img1',
        x: 0,
        y: 0,
        width: 750,
        height: 400,
        url: 'https://img.alicdn.com/imgextra/i2/3355153118/TB2TAwfmyqAXuNjy1XdXXaYcVXa-3355153118.jpg'
      }
    }]
  },
  imgHot2: {
    screenHeight: 400,
    screenWidth: 750,
    hot: [{
      data: {
        name: 'hot1',
        x: 0,
        y: 0,
        width: 750,
        height: 400,
        url: '//m.taobao.com/'
      }
    }],
    img: [{
      data: {
        name: 'img1',
        x: 0,
        y: 0,
        width: 750,
        height: 400,
        url: 'https://img.alicdn.com/imgextra/i2/3355153118/TB2TAwfmyqAXuNjy1XdXXaYcVXa-3355153118.jpg'
      }
    }]
  },

  videoUrl: 'https://cloud.video.taobao.com/play/u/2780279213/p/1/e/6/t/1/d/ld/36255062.mp4',
  videoPos: 'https://img.alicdn.com/imgextra/i2/3355153118/TB2ZoDVbmtYBeNjSspaXXaOOFXa-3355153118.jpg',
  videoHeight: 400,
  Keywords: '',


};


class MainApp extends Component {
  constructor(props) {
    super(props);
    this.pageUtils = props.pageUtils;
    this.state = {
      mds: props.mds || {},
      gdc: props.gdc || {},
      selected: 0,
    };
  }

  goTargetUrl = (url, nid) => {
    let { mds, gdc } = this.state;
    let params = {
      url: url,
      nid: nid || 0,
      widgetId: mds.widgetId,
      moduleName: mds.moduleName
    };

    this.pageUtils && this.pageUtils.goTargetUrl(params);
  };

  checkData(data, defaultKey, type, firstChildAttr) {
    let newData;
    switch (type) {
      case 'num': {
        newData = parseInt(data) ? parseInt(data) : defaultModuleData[defaultKey];
        break;
      }
      case 'string': {
        newData = data.length > 0 ? data : defaultModuleData[defaultKey];
        break;
      }
      case 'array': {
        newData = data.length && data[0][firstChildAttr].length ? data : defaultModuleData[defaultKey];
        break;
      }
      case 'goods': {
        if (typeof data === 'string') {
          newData = data.length > 0 ? data : defaultModuleData[defaultKey];
        } else {
          newData = data.length && data[0].goods.length ? data : defaultModuleData[defaultKey];
        }
        break;
      }
      case 'jsonStr': {
        try {
          newData = JSON.parse(data);
        } catch (e) {
          newData = defaultModuleData[defaultKey];
        }
        break;
      }
      default: {
        newData = data;
      }
    }
    return newData;
  }

  render() {
    const { mds } = this.state;
    let {
      tagWidth = '',
      tagSelectWidth = '',
      tagBottom = '',
      tagBg = '',
      tagSelectBg = '',
      tagMargin = '',
      sliderHeight = '',
      sliderPictures = [],

      videoHeight = '',
      videoUrl = '',
      videoPos = '',
      Keywords = '',

      imgHot1 = '',
      imgHot2 = '',

      picture = '',
      height = '',
      hasPic = '',

    } = this.state.mds.moduleData;


    // 校正数据
    const { checkData = () => {} } = this;
    tagWidth = checkData(tagWidth, 'tagWidth', 'num');
    tagSelectWidth = checkData(tagSelectWidth, 'tagSelectWidth', 'num');
    tagBottom = checkData(tagBottom, 'tagBottom', 'num');
    tagMargin = checkData(tagMargin, 'tagMargin', 'num');
    tagBg = checkData(tagBg, 'tagBg', 'string');
    tagSelectBg = checkData(tagSelectBg, 'tagSelectBg', 'string');
    const tagStyle = {
      tagWidth,
      tagSelectWidth,
      tagBottom,
      tagMargin,
      tagBg,
      tagSelectBg,
    };
    sliderHeight = checkData(sliderHeight, 'sliderHeight', 'num');
    sliderPictures = checkData(sliderPictures, 'sliderPictures', 'array', 'picUrl');

    videoUrl = checkData(videoUrl, 'videoUrl', 'string');
    videoPos = checkData(videoPos, 'videoPos', 'string');
    videoHeight = checkData(videoHeight, 'videoHeight', 'num');
    Keywords = checkData(Keywords, 'Keywords', 'string');

    // 图片热区
    imgHot1 = checkData(imgHot1, 'imgHot1', 'jsonStr');
    imgHot2 = checkData(imgHot2, 'imgHot2', 'jsonStr');

    hasPic = checkData(hasPic, 'hasPic', 'string');
    picture = checkData(picture, 'picture', 'string');
    height = checkData(height, 'height', 'num');
    // props


    const modBoxProps = {
      pageUtils: this.pageUtils,
      defaultModShow: this.state.mds.moduleData.isHome === 1 || this.state.mds.moduleData.isHome === '1',
      modName: this.state.mds.moduleData.modName,
      mds,
    };

    const props = {
      clickHot: (url, nid) => {
        this.goTargetUrl(url, nid);
      },
      mds,
    };


    const carouselProps = {
      clickHot: (url, nid) => {
        this.goTargetUrl(url, nid);
      },
      width: 750,
      height: sliderHeight,
      tagStyle,
      pages: sliderPictures,
      mds,
    };

    const singlePlayerProps = {
      playerSrc: videoUrl,
      playerPos: videoPos,
      playerKeywords: Keywords,
      playerHeight: videoHeight,
    };

    const singleVideoProps = {
      url: videoUrl,
      poster: videoPos,
      width: 750,
      height: videoHeight,
      // ...props,
    };

    const toHomeProps = {
      picture: picture,
      height: height,
      clickItem: () => {
        if (this.pageUtils && this.pageUtils.pageEmitter) {
          const emitter = this.pageUtils.pageEmitter;
          emitter.emit('goToIndex', '');
        }
        if (this.pageUtils && this.pageUtils.lift) {
          const { widgetId } = this.state.mds;
          this.pageUtils.lift.scrollTo(widgetId);
        }
        if (this.pageUtils) {
          this.pageUtils.goTop();
        }
      },
      mds,
    };

    const viewProps = {
      style: {
        width: 750,
        height: 30,
        backgroundColor: '#ffffff',
      }
    };

    return (
      <ModBox {...modBoxProps}>
        <Carousel {...carouselProps} />
        <View {...viewProps}/>
        {
          Keywords.length ? <SinglePlayer {...singlePlayerProps}/> : <OneVideo {...singleVideoProps}/>
        }
        <View {...viewProps}/>
        <ImgAddHot json={imgHot1} {...props} hotNum="1"/>
        <ImgAddHot json={imgHot2} {...props} hotNum="2"/>
        {
          hasPic === '1' && <ToHome {...toHomeProps}/>
        }
      </ModBox>
    );
  }
}

// 模块跳转包装
class ModBox extends Component {
  constructor(props) {
    super(props);
    this.pageUtils = props.pageUtils;
    this.state = {
      modShow: true,
      height: 0,
      tabsHeight: 0,
      // test: 0,
    };
    this.defaultModShow = props.defaultModShow;
    this.modName = props.modName;
    this.clickTab = this.clickTab.bind(this);
  }

  // 添加监听器，接收消息
  componentWillMount() {

    if (this.pageUtils && this.pageUtils.pageEmitter) {
      // this.setState({
      //   test: JSON.stringify(this.pageUtils.pageEmitter),
      // });
      const emitter = this.pageUtils.pageEmitter;
      emitter.on('clickTab', this.clickTab);
    }

  }

  // 组件销毁时移除监听器
  componentWillUnmount() {
    if (this.pageUtils && this.pageUtils.pageEmitter) {
      const emitter = this.pageUtils.pageEmitter;
      emitter.off('clickTab', this.clickTab);
    }
  }

  componentDidMount() {
    this.getHeight();
    setTimeout(this.showPage, 1000);
  }

  getHeight = () => {
    const tabRefs = this.modName;
    const delay = navigator.platform === 'iOS' ? 40 : 200;

    this.setState({
      test: delay
    });
    setTimeout(() => {
      if (isWeex) {
        this.setState({
          test: '22222'
        });
        let domModule = require('@weex-module/dom');
        new Promise((resolve, reject) => {
          domModule.getComponentRect(findDOMNode(this.refs[tabRefs]), (option) => {
            resolve(option.size.height);
            this.setState({
              test: option.size.height
            });
          });
        }).then(res => {
          this.setState({
            test: `${res}`,
            tabsHeight: res,
          });
        });

        this.setState({
          test: '333333'
        });
      } else {
        let height = findDOMNode(this.refs[tabRefs]).clientHeight * 2;
        this.setState({
          tabsHeight: height,
        });
      }
    }, delay);
  };

  showPage = () => {
    if (this.modName === 'page1' || this.defaultModShow) {
      this.setState({
        height: this.state.tabsHeight,
      });
    }
  };


  clickTab(params) {
    const { modName } = this;

    if (modName.length && modName === params) {
      this.setState({
        modShow: true,
        // test: this.state.tabsHeight,
        height: this.state.tabsHeight,
      });
    } else {
      this.setState({
        modShow: false,
        height: 0,
        // test: 800,
      });
    }
  }

  render() {
    const { modShow, height, test } = this.state;
    const { mds } = this.props;

    const boxProps = {
      'data-role': mds.moduleName,
      'data-spmc': `${mds.moduleName}_${mds.widgetId}`,
      style: {
        backgroundColor: '#ffffff',
        height: height,
      },
    };

    return (
      <View {...boxProps}>
        <View ref={this.modName}>
          {
            modShow && this.props.children
          }
        </View>
      </View>
    );
  }
}

// 轮播
const carouselStyles = {
  wrapper: {
    position: 'relative',
  },
  tagBox: {
    position: 'absolute',
    left: 0,
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'row'
  }
};
class CarouselBox extends Component {

  constructor(props) {
    super(props);
    this.state = {
      selected: 0
    };
  }

  onSliderChange(index) {
    const { onSliderChange = () => {} } = this.props;
    onSliderChange(index);
    this.setState({
      selected: index.index
    });
  }

  onTagClick(index) {
    this.refs.Slider.slideTo(index);
    this.setState({
      selected: index
    });
  }

  render() {
    const {
      // mds,
      // width = 750,
      // height = 750,
      width,
      height,
      autoplayTime = 3000,
      children,
      loop = true,
      tagShow = true,
      tagStyle = {},
    } = this.props;
    const {
      tagWidth = 10,
      tagSelectWidth = 20,
      tagBottom = 10,
      tagBg = '#ffffff',
      tagSelectBg = '#ffffff',
      tagMargin = 10,
    } = tagStyle;
    const isShowTag = tagShow === true || tagShow === 'true';

    const boxProps = {
      style: {
        ...carouselStyles.wrapper,
        width,
        height,
      },
      // ...stopTouchEvents,
    };
    const sliderProps = {
      width: `${width}rem`,
      height: `${height}rem`,
      ref: 'Slider',
      autoPlay: autoplayTime > 0,
      loop,
      autoplayTimeout: autoplayTime ? parseFloat(autoplayTime) : 0,
      showsPagination: false,
      onChange: this.onSliderChange.bind(this)
    };
    const tagBoxProps = {
      style: {
        ...carouselStyles.tagBox,
        height: tagWidth,
        width,
        top: height - tagWidth - tagBottom,
      }
    };

    return (
      <View {...boxProps}>
        <Slider {...sliderProps}>
          {
            children.map((item, index) => {
              return <View key={index}>{item}</View>;
            })
          }
        </Slider>
        {
          isShowTag &&
          <View {...tagBoxProps}>
            {
              children.map((item, index) => {

                const props = {
                  key: `tag_${index}`,
                  style: {
                    width: index === this.state.selected ? tagSelectWidth : tagWidth,
                    height: tagWidth,
                    borderRadius: tagWidth / 2,
                    marginRight: tagMargin,
                    backgroundColor: index === this.state.selected ? tagSelectBg : tagBg,
                  },
                  onPress: this.onTagClick.bind(this, index)
                };
                return <Touchable {...props}/>;
              })
            }
          </View>
        }

      </View>
    );
  }
}
class Carousel extends Component {
  render() {
    const {
      mds,
      pages,
      width,
      height,
      carNum = '1',
      tagShow = true,
      tagStyle,
      clickHot,
      tab = 1,
    } = this.props;

    const sliderProps = {
      width,
      height,
      tagShow,
      tagStyle,
    };

    return (
      <CarouselBox {...sliderProps}>
        {
          pages.map((item, index) => {
            const { hotUrl, picUrl } = item;

            // const spmdId = `${tab}_${index + 1}`;
            const spmdId = `${tab}_${carNum}_${index}`;
            const spmd = `${mds.moduleName}_${mds.widgetId}_${spmdId}`;
            const touchProps = {
              'data-spmd': spmd,
              style: {
                width,
                height,
              },
              onPress: () => {
                clickHot(hotUrl, spmdId);
                // clickHot(hotUrl);
              },
            };
            const picProps = {
              source: {
                uri: picUrl,
              },
              style: {
                width,
                height,
              },
              lazyload: true,
            };

            return (
              <Touchable {...touchProps}>
                <Picture {...picProps}/>
              </Touchable>
            );
          })
        }
      </CarouselBox>
    );
  }
}

// 单个视频Player组件
const playerStyle = {
  // player: {
  //   width: 750,
  //   height: 400,
  // },
  keyArray: {
    position: 'absolute',
    right: 40,
    top: 20,
    flexDirection: 'row',
    zIndex: 1,
  },
  keyText: {
    textAlign: 'center',
    height: 46,
    borderRadius: 19,
    paddingLeft: 19,
    paddingRight: 19,
    marginLeft: 6,
    lineHeight: 46,
    fontSize: 24,
    backgroundColor: 'rgba(255,255,255,0.5)',
    color: '#000000',
  },
  picture: {
    width: 200,
    height: 60,
  },
};
class SinglePlayer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isPlaying: false,
    };
  }

  render() {
    const { playerSrc, playerPos, playerKeywords, playerHeight, } = this.props;
    const { isPlaying } = this.state;
    let keyArray = [];
    let hasKey = true;
    playerKeywords ? keyArray = playerKeywords.split(',') : hasKey = false;

    const playerProps = {
      style: {
        ...playerStyle.player,
        width: 750,
        height: playerHeight,
      },
      poster: playerPos,
      src: playerSrc,
      onVideoPlay: () => {
        this.setState({isPlaying: true});
      },
      onVideoPause: () => {
        this.setState({isPlaying: false});
      },

    };

    return (
      <View style={{width: 750, height: playerHeight}}>
        <Player {...playerProps} controls hasFullScreen startBtn/>
        <View style={playerStyle.keyArray}>
          {
            hasKey && !isPlaying && keyArray.map(word => {
              return (
                <Text style={playerStyle.keyText}>#{word}</Text>
              );
            })
          }
        </View>
      </View>

    );
  }
}

// 单个视频video组件
const oneVideoStyle = {
  box: {
    position: 'absolute',
    top: 0,
    left: 0,
  },
};
class OneVideo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isPlaying: false,
    };
  }


  render() {
    let { url, poster, width = 750, height = 400, muted = false, } = this.props;
    const { isPlaying } = this.state;

    const videoProps = {
      style: {
        width: width,
        height: height,
      },
      muted: muted,
      src: url,
      controls: true,
      autoPlay: true,
      autoplay: true,
      ref: 'video',

      // onVideoPlay: () => {
      //   // this.setState({isPlaying: true});
      //   this.isPlay(true, index);
      // },
      // onVideoPause: () => {
      //   // this.setState({isPlaying: false});
      //   this.isPlay(false, index);
      // },
      // onAppear: () => {
      //   this.refs.player.refs.video.play();
      // },
      // onDisappear: () => {
      //   this.refs.player.refs.video.pause();
      // },
      // ref: 'player',
    };

    const touchProps = {

      style: {
        ...oneVideoStyle.box,
        width: width,
        height: height,
      },
      onPress: () => {
        // this.refs.video.play();
        this.setState({
          isPlaying: true,
        });
      }
    };
    const posterProps = {
      style: {
        width: width,
        height: height,
        ...oneVideoStyle.box,
      },
      source: {
        uri: poster,
      },
      lazyload: true,
    };
    return (
      <View style={{ width: width, height: height}} >
        {
          isPlaying ? <video {...videoProps}/> :
            <Touchable {...touchProps}>
              <Picture {...posterProps}/>
            </Touchable>
        }
      </View>
    );
  }
}

// 图与热区
const ImgAddHotStyles = {
  boxStyle: {
    position: 'relative'
  },
  itemStyle: {
    position: 'absolute'
  }
};
class ImgAddHot extends Component {

  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    const { boxStyle, itemStyle, } = ImgAddHotStyles;

    const {
      json = {screenHeight: 100, screenWidth: 750, hot: [], img: []},
      clickHot = () => {}, mds, hotNum,
    } = this.props;

    const scrollProps = {
      style: {
        width: 750,
        height: parseFloat(json.screenHeight),
        backgroundColor: '#ffffff',
      },
      horizontal: true,
      showsHorizontalScrollIndicator: false,
    };
    const boxProps = {
      style: {
        ...boxStyle,
        height: parseFloat(json.screenHeight),
        width: parseFloat(json.screenWidth),
        backgroundColor: '#ffffff',
      }
    };

    return (
      <ScrollView {...scrollProps}>
        <View {...boxProps}>
          {
            json.img.map((item) => {
              const props = {
                style: {
                  ...itemStyle,
                  width: parseFloat(item.data.width),
                  height: parseFloat(item.data.height),
                  top: parseFloat(item.data.y),
                  left: parseFloat(item.data.x)
                },
                lazyload: true,
                source: { uri: item.data.url }
              };
              return <Picture {...props} />;
            })
          }
          {
            json.hot.map((item, index) => {
              const spmdId = `${hotNum}_${index}_hotImg6`;
              const spmd = `${mds.moduleName}_${mds.widgetId}_${spmdId}`;
              const props = {
                'data-spmd': spmd,
                style: {
                  ...itemStyle,
                  width: parseFloat(item.data.width),
                  height: parseFloat(item.data.height),
                  top: parseFloat(item.data.y),
                  left: parseFloat(item.data.x)
                },
                onPress: (e) => {
                  clickHot(item.data.url, spmdId);
                  e.stopPropagation && e.stopPropagation();
                }
              };
              return <Touchable {...props} />;
            })
          }
        </View>
      </ScrollView>

    );
  }
}

//  返回首页
class ToHome extends Component {

  render() {
    const {
      picture, height, clickItem = () => {},
    } = this.props;


    const boxProps = {
      style: {
        width: 750,
        height: height,
      },
      onPress: () => {
        clickItem();
      }

    };

    const picProps = {
      source: {
        uri: picture.length !== 0 && picture,
      },
      style: {
        width: 750,
        height: height,

      },
      lazyload: true,
    };

    return (
      <Touchable {...boxProps}>
        <Picture {...picProps}/>
      </Touchable>
    );
  }
}

export default MainApp;

